package cn.fzkj.gulimall.auth.strategy.login;

import cn.fzkj.gulimall.auth.entity.GiteeUserEntity;
import cn.fzkj.gulimall.auth.entity.base.SocialUser;
import cn.fzkj.gulimall.auth.enums.LoginType;
import cn.fzkj.gulimall.auth.exception.OauthLoginException;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @DESCRIPTION gitee登陆
 * @Author yaya
 * @DATE 2022/8/27
 */
@Slf4j
public class GiteeStrategy implements LoginStrategy {

    private static final String accessUrl = "https://gitee.com/oauth/token?grant_type=authorization_code&" +
            "client_id=b0270d6040972be1576a19f74bb2002d3ea957382f473419c26270d0d1b87787&redirect_uri=http%3A%2F%2F127.0.0.1%3A7000%2Foauth%2Fgitee&code=";
    private static final String client_secret = "{\"client_secret\":\"d4429388630aafef9b2c30bc103a8cadcc69dbbe2e86b980d903971bf97763bd\"}";

    private static final String userInfoUrl = "https://gitee.com/api/v5/user?access_token=";

    @Override
    public SocialUser getUserInfo(String code) {

        String accessToken = getAccessToken(code);
        if (StringUtils.isEmpty(accessToken)){
            throw new OauthLoginException("request gitee.com for access token fail.");
        }
        return getUserInfoFromRemote(accessToken);
    }

    @Override
    public LoginType supportType() {
        return LoginType.GITEE;
    }

    private String getAccessToken(String code){
        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost(accessUrl + code);

        StringEntity stringEntity = new StringEntity(client_secret, "utf-8");
        stringEntity.setContentType("application/json");
        httpPost.setEntity(stringEntity);

        String content = "";
        try {
            CloseableHttpResponse response = client.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获取响应实体
                HttpEntity resTestEntity = response.getEntity();
                // 输出响应
                content = EntityUtils.toString(resTestEntity, "utf-8");

                JSONObject jsonObject = JSON.parseObject(content);
                return (String) jsonObject.get("access_token");
            }else {
                log.warn("request for gitee.com fail.");
            }
            response.close();
        } catch (IOException e) {
            log.warn("request login for gitee.com throw exception. {}", e);
        }

        try {
            client.close();
        } catch (IOException e) {
            log.warn("close http response fail.");
        }
        return "";
    }

    /**
     * 通过访问令牌获取用户信息
     * @param accessToken
     * @return
     */
    private GiteeUserEntity getUserInfoFromRemote(String accessToken){
        CloseableHttpClient client = HttpClients.createDefault();

        HttpGet httpGet = new HttpGet(userInfoUrl + accessToken);
        try {
            CloseableHttpResponse response = client.execute(httpGet);
            String json = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(json);

            GiteeUserEntity user = new GiteeUserEntity();
            user.setUserId(jsonObject.getLong("id"));
            user.setEmail(jsonObject.getString("email"));
            user.setUserName(jsonObject.getString("name"));

            return user;
        } catch (Exception e) {
            log.warn("request gitee.com for user information fail.{}", e);
        }
        return new GiteeUserEntity();
    }
}
